//
//  UserCouponViewController.m
//  demoapp
//
//  Created by MingmingSun on 15/9/11.
//  Copyright (c) 2015年 pingplusplus. All rights reserved.
//

#import "UserCouponViewController.h"
#import "PullingRefreshTableView.h"

@interface UserCouponViewController ()<UITableViewDataSource,UITableViewDelegate,PullingRefreshTableViewDelegate>

@property(nonatomic,strong) NSMutableArray *barberArray;

@property(nonatomic,weak) IBOutlet PullingRefreshTableView *listView;
@property(assign,nonatomic) BOOL refreshing;
@property(assign,nonatomic) NSInteger page;

@property(nonatomic,strong) IBOutlet UIButton *button1;
@property(nonatomic,strong) IBOutlet UIButton *button2;
@property(nonatomic,strong) IBOutlet UIButton *button3;

@property(nonatomic,strong) IBOutlet UILabel *leftLabel;
@property(nonatomic,strong) IBOutlet UILabel *middleLabel;
@property(nonatomic,strong) IBOutlet UILabel *rightLabel;

@property(nonatomic,strong) IBOutlet UILabel *shuLabel1;
@property(nonatomic,strong) IBOutlet UILabel *shuLabel2;

@property(nonatomic,assign) int buttonIndex;

-(IBAction)buttonPressed:(id)sender;

@end

@implementation UserCouponViewController

@synthesize listView;
@synthesize refreshing = _refreshing;
@synthesize page = _page;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"我的优惠券";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.barberArray = [NSMutableArray array];
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.listView.pullingDelegate = self;
    [self.listView awakeWhenXIB:self.listView.frame];
    
    self.buttonIndex = 1;
    [self arrangeButtons];
}

-(IBAction)buttonPressed:(id)sender{
    self.buttonIndex = [sender tag];
    [self arrangeButtons];
}

-(void)arrangeButtons{
    switch (self.buttonIndex) {
        case 1:{
            [self.button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [self.button2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [self.button3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.leftLabel.backgroundColor = [UIColor redColor];
            self.middleLabel.backgroundColor = [UIColor grayColor];
            self.rightLabel.backgroundColor = [UIColor grayColor];
            self.shuLabel1.backgroundColor = [UIColor redColor];
            self.shuLabel2.backgroundColor = [UIColor grayColor];
        }
            break;
        case 2:{
            [self.button1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [self.button2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [self.button3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.leftLabel.backgroundColor = [UIColor grayColor];
            self.middleLabel.backgroundColor = [UIColor redColor];
            self.rightLabel.backgroundColor = [UIColor grayColor];
            self.shuLabel1.backgroundColor = [UIColor redColor];
            self.shuLabel2.backgroundColor = [UIColor redColor];
        }
            break;
        case 3:{
            [self.button1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [self.button2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [self.button3 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            self.leftLabel.backgroundColor = [UIColor grayColor];
            self.middleLabel.backgroundColor = [UIColor grayColor];
            self.rightLabel.backgroundColor = [UIColor redColor];
            self.shuLabel1.backgroundColor = [UIColor grayColor];
            self.shuLabel2.backgroundColor = [UIColor redColor];
        }
            break;
            
        default:
            break;
    }
    [self fetchCouponLists];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)fetchCouponLists {
    NSDictionary *para;
    switch (self.buttonIndex) {
        case 1:
            para= @{@"used":@"no",
                    @"expired":@"no",
                    @"token":APPALL.myUserItem.token};
            break;
        case 2:
            para= @{@"used":@"yes",
                    @"expired":@"no",
                    @"token":APPALL.myUserItem.token};
            break;
        case 3:
            para= @{@"used":@"no",
                    @"expired":@"yes",
                    @"token":APPALL.myUserItem.token};
            break;
        default:
            break;
    }
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"coupon_list" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        [self.listView tableViewDidFinishedLoading];
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    [_barberArray removeAllObjects];
                    NSArray *cityArray = [aSucData objectForKey:@"coupon"];
                    for (NSDictionary *dic in cityArray) {
                        [_barberArray addObject:dic];
                    }
                    [listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.barberArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    inde= @"CouponID";
    cell = [tableView dequeueReusableCellWithIdentifier:inde];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CouponCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
    UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
    NSDictionary *cacheItem = [_barberArray objectAtIndex:indexPath.row];
    lab1.text = [NSString stringWithFormat:@"%.2f",[[cacheItem valueForKey:@"price"] floatValue]];
    float price = [[cacheItem valueForKey:@"minCost"] floatValue];
    if(price <= 0)
        lab2.text = @"无限制使用";
    else
        lab2.text = [NSString stringWithFormat:@"满%.2f元可用",price];
    lab3.text = [NSString stringWithFormat:@"有效期至:%@",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"scrapTime"]]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView{
    self.refreshing = YES;
    [self fetchCouponLists];
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView{
    [self fetchCouponLists];
}

#pragma mark - Scroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.listView tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.listView tableViewDidEndDragging:scrollView];
}

@end